package com.lishem.carl._07tree;

import com.lishem.common.TreeNode;

import java.util.Stack;

/**
 * https://leetcode.cn/problems/symmetric-tree/
 * <p>
 * 给你一个二叉树的根节点 root ， 检查它是否轴对称。
 */
public class _15LetCode101_对称二叉树 {

    public boolean isSymmetric(TreeNode root) {
        Stack<TreeNode> leftStack = new Stack<>();
        Stack<TreeNode> rightStack = new Stack<>();
        if (root == null || root.left == null && root.right == null) {
            return true;
        }
        if (root.left != null) {
            leftStack.push(root.left);
        }
        if (root.right != null) {
            rightStack.push(root.right);
        }

        while (!leftStack.isEmpty() && !rightStack.isEmpty()) {
            TreeNode left = leftStack.pop();
            TreeNode right = rightStack.pop();
            if (left == null && right == null) {
                continue;
            }
            if (left == null || right == null || left.val != right.val) {
                return false;
            }
            leftStack.push(left.right);
            leftStack.push(left.left);
            rightStack.push(right.left);
            rightStack.push(right.right);
        }
        return leftStack.isEmpty() && rightStack.isEmpty();
    }

    public static void main(String[] args) {
        _15LetCode101_对称二叉树 sol = new _15LetCode101_对称二叉树();
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.left.left = new TreeNode(3);
        root.left.right = new TreeNode(4);
        root.right = new TreeNode(2);
        root.right.left = new TreeNode(4);
        root.right.right = new TreeNode(3);
        System.out.println(sol.isSymmetric(root));

    }
}
